// pages/caseSrc/caseSrc.js
import request from '../../utils/config.js';
import formatDate from '../../utils/util.js';
import cityList from '../../utils/vendor/cityList.js';
let QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
let qqmapsdk;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: wx.getSystemInfoSync().windowHeight - 40,
    index:'0',
    city: ["全国"],
    // province: '',
    caseSrcList: [],
    pageNum: 1,
    totalPage: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'D7GBZ-PKZR4-TZSU4-X753B-XU74Q-J4FPO' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
    });

    let city = this.data.city;
    for (let i in cityList) {
      city.push(i); //属性
    }
    this.setData({
      city: city
    })
    
    this.matchCaseList(this.data.pageNum,'')
  },

  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let city = this.data.city;
    let index = e.detail.value;
    this.setData({
      chooseAdd: true,
      index: index,
      // province: city[index]
    })
    this.matchCaseList(1, city[index])
  },
  goMyCase: function() {
    wx.navigateTo({
      url: 'myCaseSrc/myCaseSrc',
    })
  },

  matchCaseList: function (pageNum, province) {
    let _this = this;
    let headerInfo = {
      pageNum: pageNum,
      pageSize: "10",
      sessionId: app.globalData.sessionId,
    }
    let provinceName = province;
    if (province == "全国"){
      provinceName = "";
    }
    let bodyInfo = {
      province: provinceName,
      city: ""
    }
    if (pageNum == 1) {
      this.setData({
        caseSrcList: []
      });
    }
    wx.showLoading({ title: '加载中...', mask: true })
    request.requestLogin_api("matchCaseList", headerInfo, bodyInfo, (obj) => {
      console.log("案件列表==", obj)
      wx.hideLoading()
      if (obj.data.isSuccess == "T") {
        if (pageNum == 1 && JSON.parse(obj.data.body).caseInfoList.length == 0) {
          wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
        }
        let totalNum = obj.data.totalNum;
        let pageNum = obj.data.pageNum;
        let totalPage = obj.data.totalPage;
        
        let tempArr = JSON.parse(obj.data.body).caseInfoList;
        // console.log("获取案件列表成功==", tempArr)
        if (tempArr.length > 0) {
          let tempList = _this.data.caseSrcList;
          tempArr.forEach(function (e) {
            e.caseAmt = formatDate.filterFormatAmt(e.caseAmt * 1 / 10000);
            e.status = formatDate.investStatusFilter(e.status);
            e.caseTypeId = formatDate.filterCaseTypeId(e.caseTypeId)

            let address = [];
            e.caseLbsInfos.forEach(function (y) {
              let str = '';
              if (y.province) {
                str = y.province
              }
              if (y.city) {
                str += ' ' + y.city
              }
              if (y.country) {
                str += ' ' + y.country
              }
              address.push(str)
            })
            address = address.toString();
            if (!address) {
              address = '暂无'
            } 
            e.address = address;

            tempList.push(e)
          });
          
          //保存时间
          _this.setData({
            caseSrcList: tempList,
            pageNum: pageNum,
            totalPage: totalPage
          });
          wx.hideLoading();
        } else {
          wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
        
        }
      } else {
        wx.hideLoading();
        wx.showModal({
          title: "加载失败",
          content: obj.data.errorMsg,
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("获取案件列表失败==", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  //获取案件类型数据
  queryCaseTypeList: function (){
    var serviceName = "queryCaseTypeList";
    var headerInfo = {}, bizInfo = {};
    headerInfo.pageNum = '';
    headerInfo.pageSize = '';
    headerInfo.sessionId = "";
    $.ajax({
      url: '/biz.ajax',
      method: 'get',
      cache: false,
      headers: {
        "Accept": "text/plain; charset=utf-8",
        "Content-Type": "text/plain; charset=utf-8"
      },
      data: {
        'serviceName': serviceName,
        'headerInfo': JSON.stringify(headerInfo),
        'bizInfo': JSON.stringify(bizInfo)
      },
      success: function (data, textStatus, jqXHR) {
        var returnData = JSON.parse(data);
        if (returnData.isSuccess == "T") {
          var tempCaseTypeList = JSON.parse(returnData.body).caseTypeList;
          //存储案件类型数据
          localStorage.setItem("caseTypeListCache", JSON.stringify(tempCaseTypeList));
          queryCaseStageList();
        }
      },
      error: function (xhr, textStatus) {
        console.log('失败=', xhr)
      }
    })

    request.requestLogin_api("queryCaseTypeList", headerInfo, bodyInfo, (obj) => {
      if (obj.data.isSuccess == "T") {
        let caseInfoList = JSON.parse(obj.data.body).caseInfoList;
        // console.log("获取案件列表成功==", caseInfoList)
        // let caseInfoList = new Array();
        if (caseInfoList.length > 0) {
          caseInfoList.forEach(function (e) {
            e.caseAmt = formatDate.filterFormatAmt(e.caseAmt * 1 / 10000);
            e.status = formatDate.investStatusFilter(e.status);
            e.caseTypeId = filterCaseTypeId(e.caseTypeId)
          });
          //保存时间
          _this.setData({
            caseSrcList: caseInfoList
          });
          wx.hideLoading();
        } else {
          _this.setData({
            caseData: false
          });
          // _this.getCardLoginInfo(_this);
        }
      } else {
        wx.hideLoading();
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("获取案件列表失败==", obj)
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  //获取地理位置
  selectLocation: function () {
    let vm = this;
    vm.getUserLocation();
  },

  //获取地理位置
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        // vm.setData({
        //   province: province,
        //   city: city,
        //   latitude: latitude,
        //   longitude: longitude
        // })
        //获取省值
        // if (province == "上海市" || province == "北京市" || province == "天津市" || province == "重庆市"){
          // province = province.replace(/市/g,"");
        // }
        province = province.substring(0, province.length - 1);
        let cityList = vm.data.city;
        let tempIndex = 0;
        for(let i=0;i<cityList.length;i++){
          if (province == cityList[i]){
            tempIndex = i;
            break;
          }
        }
        vm.setData({
          index: tempIndex
        });
        vm.matchCaseList(1, province)
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.matchCaseList(this.data.pageNum, '');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.matchCaseList(this.data.pageNum, '')
  },
  upper: function (e) {
    // console.log("顶部=", e)
  },
  lower: function(e) {
    // console.log("底部=", e)
    let pageNum = this.data.pageNum;
    let totalPage = this.data.totalPage;
    // console.log('pageNum', pageNum)
    // console.log('totalPage', totalPage)
    if (pageNum < totalPage) {
      this.matchCaseList(pageNum * 1 + 1,'')
    } else {

    }
  },
  goCaseSrcDetail: function(e) {
    console.log('id=====', e.currentTarget.dataset)
    let caseId = e.currentTarget.dataset.id;
    let isapply = e.currentTarget.dataset.isapply;
    wx.navigateTo({
      url: 'caseDetail/caseDetail?caseId=' + caseId + '&isapply=' + isapply,
      // url: '../caseDetail/caseDetail',
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})